package com.jin.webvideo.service;

import com.jin.webvideo.base.dc.AsynExecutor;
import com.jin.webvideo.base.dc.DCClassLoaderCreator;
import com.jin.webvideo.base.dc.DSExecutor;
import com.jin.webvideo.mapper.ParserMapper;
import com.jin.webvideo.util.base.StringUtil;
import com.jin.webvideo.util.consts.ConfigConst;
import javassist.compiler.CompileError;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.List;

/**
 * 刷新服务
 * @author biao532
 * @date 2023/12/04 12:38
 **/
@Service
public class RefreshService {
    @Autowired
    private ParserMapper mapper;
    @Autowired
    private ConfigService configService;

    /**
     * AccessControl的策略刷新
     * @return
     */
    public String accessControl() {
        String mainClass = configService.configByGroupIdAndAttrid(ConfigConst.REFRESH, ConfigConst.ACCESS);
        if (StringUtil.isEmpty(mainClass)) {
            return "尚未配置";
        }
        String url = mapper.findUrlByName(mainClass);
        if (StringUtil.isEmpty(url)) {
            return "尚未配置.";
        }
        String classpath = configService.configByGroupIdAndAttrid(ConfigConst.REFRESH, ConfigConst.CLASSPATH);
        List<String> args = Arrays.asList();
        if (!StringUtil.isEmpty(classpath)) {
            args = Arrays.asList("-classpath", classpath);
        }
        try {
            DCClassLoaderCreator creator = DCClassLoaderCreator.creator();
            creator.compile(args, url);
            int stats = AsynExecutor.singleton().submit(new DSExecutor(creator, mainClass) {
                @Override
                protected Object[] args() {
                    return new Object[0];
                }
            });
            return switch (stats) {
                case AsynExecutor.STATS_SUCCESS -> "刷新成功";
                case AsynExecutor.STATS_FAIL -> "执行失败，请检查日志";
                case AsynExecutor.STATS_TIMEOUT -> "执行超时，请检查是否脚本存在耗时操作";
                default -> "执行失败，请详细信息查看相关日志";
            };
        }
        catch (CompileError compileError) {
            compileError.printStackTrace();
        }
        return "编译失败";
    }
}
